using System;
using System.IO;
using System.Net;
using System.Text;

namespace Google.Apps.Provisioning.Utilities
{
    /// <summary>
    /// Provides convenience methods for issuing a HTTP "POST" command and returning the results.
    /// </summary>
    public class WebUtility
    {
        private WebUtility() {;}

        public static HttpWebResponse DoHttpPost( string targetUrl, string postBody )
        {
            HttpWebRequest request = 
                (HttpWebRequest) WebRequest.Create( targetUrl );

            request.Method = "POST";

            Encoding encoding = Encoding.GetEncoding( "ISO-8859-1" );

            byte [] postBuffer = encoding.GetBytes( postBody );

            request.ContentLength = postBuffer.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            using( Stream requestStream = request.GetRequestStream() )
            {
                requestStream.Write( postBuffer, 0, postBuffer.Length );
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch ( WebException we )
            {
                response = (HttpWebResponse)we.Response;
            }

            return response;
        }

        public static void DoHttpPost( string targetUrl, string postBody, 
            out HttpStatusCode resultCode, out string resultBody )
        {
            HttpWebResponse response = DoHttpPost( targetUrl, postBody );
        
            using( StreamReader reader = new StreamReader( response.GetResponseStream()) )
            {
                resultCode = response.StatusCode;
                resultBody = reader.ReadToEnd();
            }
        }
    }    
}
